﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using FluentFTP.Configuration;
using FluentFTP.Model;
using FluentFTP.View;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;

namespace FluentFTP.ViewModel
{
    internal class ServersViewModel : NotificationObject
    {
        private ObservableCollection<FtpServerInfo> servers;
        public ObservableCollection<FtpServerInfo> Servers
        {
            get { return servers; }
            set
            {
                servers = value;
                RaisePropertyChanged(() => Servers);
            }
        }

        private FtpServerInfo selectedServer;

        public FtpServerInfo SelectedServer
        {
            get { return selectedServer; }
            set
            {
                selectedServer = value;
                RaisePropertyChanged(() => SelectedServer);
                raiseAllCommandsCanExecuteChanged();
            }
        }

        public DelegateCommand AddServer { get; private set; }
        public DelegateCommand DeleteSelectedServer { get; private set; }
        public DelegateCommand EditSelectedServer { get; private set; }

        public ServersViewModel()
        {
            AddServer = new DelegateCommand(() =>
                {
                    var window = new EditServerView();
                    window.ShowDialog();
                    Refresh();
                });

            DeleteSelectedServer = new DelegateCommand(() =>
                {
                    Settings.Servers.Remove(Settings.Servers.First(x => x.Id == SelectedServer.Id));
                    Refresh();
                },
                () => SelectedServer != null);

            EditSelectedServer = new DelegateCommand(() =>
                {
                    var window = new EditServerView(SelectedServer);
                    window.ShowDialog();
                    Refresh();
                },
                () => SelectedServer != null);

            Refresh();
        }

        public void Refresh()
        {
            Servers = new ObservableCollection<FtpServerInfo>(Settings.Servers);
            raiseAllCommandsCanExecuteChanged();
        }

        private void raiseAllCommandsCanExecuteChanged()
        {
            AddServer.RaiseCanExecuteChanged();
            EditSelectedServer.RaiseCanExecuteChanged();
            DeleteSelectedServer.RaiseCanExecuteChanged();
        }

    }
}
